<?php

namespace app\wechat\Controller;


use think\db;
use think\Exception;
use think\exception\PDOException;
use think\Log;
use think\Request;
use app\admin\model\PhotoModel;
use EasyWeChat\Factory;
use EasyWeChat\Kernel\Messages\Text;
use EasyWeChat\Kernel\Messages\Transfer;

class Receive extends \Wkidt\think5\Controller{



    public  function  index(){
        define("TOKEN", "wkidt");
        //$this->valid();
        $this->responseMsg();
    }


    public function valid()
    {
        $echoStr = $_GET["echostr"];
        // file_put_contents('bb.txt', $echoStr.'----');
        //valid signature , option
        if($this->checkSignature()){
            ob_clean();
            echo $echoStr;
            exit;
        }
    }

    private function checkSignature()
    {
        // you must define TOKEN by yourself
        if (!defined("TOKEN")) {
            throw new Exception('TOKEN is not defined!');
        }

        $signature = $_GET["signature"];
        $timestamp = $_GET["timestamp"];
        $nonce = $_GET["nonce"];

        //file_put_contents('ccc.txt', $signature.'----'.$timestamp.'----'.$nonce);

        $token = TOKEN;
        $tmpArr = array($token, $timestamp, $nonce);
        // use SORT_STRING rule
        sort($tmpArr, SORT_STRING);
        $tmpStr = implode( $tmpArr );
        $tmpStr = sha1( $tmpStr );

        if( $tmpStr == $signature ){
            return true;
        }else{
            return false;
        }
    }

    /**
     *
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidArgumentException
     */
    public function responseMsg(){
        $app = Factory::officialAccount(config("EasyWechetConfig"));
        $app->server->push(function ($message) {
            $msg=var_export($message,true);
            Log::record($msg);
            switch ($message['MsgType']) {
                case 'event':
                    if ($message['Event'] == 'subscribe') {
                        //新增粉丝到数据库，并且生成关注二维码
                        $this->subscribe($message['FromUserName']);
                        //发送消息欢迎消息
                        $text = new Text('您好！欢迎关注oscar亲子之家！');
                        return $text;
                    }
                    if ($message['Event'] == 'unsubscribe') {
                        //新增粉丝到数据库，并且生成关注二维码
                        $this->unsubscribe($message['FromUserName']);
                    }

                    if ($message['Event'] == 'user_get_card') {
                        //用户领取会员卡

                        $this->user_get_card($message['FromUserName'],$message['CardId'], $message['UserCardCode']);
                        Log::record($message['Event']);
                    }

                    if ($message['Event'] == 'user_view_card') {
                        //用户打开会员卡

                        $this->user_view_card($message['FromUserName'],$message['CardId'], $message['UserCardCode']);
                        Log::record($message['Event']);
                    }

                    if ($message['Event'] == 'submit_membercard_user_info') {
                        //用户激活

                        $this->submit_membercard_user_info($message['FromUserName'],$message['CardId'], $message['UserCardCode']);
                        Log::record($message['Event']);
                    }

                    if ($message['Event'] == 'user_del_card') {
                        //删除会员卡
                        $this->user_del_card($message['FromUserName'], $message['UserCardCode']);
                    }
                    break;
                case 'text':
                    return new Transfer();
                    break;

                // ... 其它消息
                default:
                    return new Transfer();
                    break;
            }
        });


        $response = $app->server->serve()->send();

        return $response;
    }




    /**
     * 用户关注
     */
    public function subscribe($open_id=''){

        if(!empty($open_id)){
            $this->addmember($open_id);
        }

    }

    /**
     * 用户取消关注
     */
    public function unsubscribe($open_id=''){
        Db::name('member')->where('openid',$open_id)->update(['subscribe'=>0]);
    }


    /**
     * 添加用户信息
     */
    public function addmember($open_id=''){
        $app = Factory::officialAccount(config("EasyWechetConfig"));
        $users=$app->user->get($open_id);

        //判断用户知否关注
        if($users['subscribe']==0){
            $data['subscribe'] = $users['subscribe'];
            $data['openid'] = $users['openid'];
        }elseif ($users['subscribe']==1){
            $data['subscribe'] = $users['subscribe'];
            $data['openid'] = $users['openid'];
            $data['nickname'] = $users['nickname'];
            $data['sex'] = $users['sex'];
            $data['language'] = $users['language'];
            $data['city'] = $users['city'];
            $data['province'] = $users['province'];
            $data['country'] = $users['country'];
            $data['headimgurl'] = $users['headimgurl'];
            $data['subscribe_time'] = $users['subscribe_time'];
            $data['remark'] = $users['remark'];
            $data['groupid'] = $users['groupid'];
            $data['tagid_list'] = json_encode($users['tagid_list']);
            $data['subscribe_scene'] = $users['subscribe_scene'];
            $data['qr_scene'] = $users['qr_scene'];
            $data['qr_scene_str'] = $users['qr_scene_str'];
        }else{
            return null;
        }

        // 判断会员是否已经添加,如果没有记录，则添加，如果有，则更新
        $wx_user=Db::name('member')->where(array('openid'=> $open_id))->find();
        if(empty($wx_user)){
            $rs=Db::name('member')->insertGetId($data);
        }else{
            $rs=Db::name('member')->where(array('openid'=> $open_id))->update($data);
        }
    }

    /**
     * 用户领取会员卡
     * @return string
     */
    public  function  user_get_card($openid ,$CardId ,$UserCardCode){

        if($openid){
            $this->addmember($openid);
        }
        // 更新会员的会员卡信息
        $where['openid'] = $openid;
        $data['CardId'] = $CardId;
        $data['member_card'] = $UserCardCode;
        //Log::record('会员卡更新'.$openid.$CardId.$UserCardCode);
        $res = Db::name('member')->where($where)->update($data);
        return $res;
    }

    /**
     * 用户打开会员卡
     * @return string
     */
    public  function  user_view_card($openid ,$CardId ,$UserCardCode){

        if($openid){
            $this->addmember($openid);
        }
        // 更新会员的会员卡信息
        $data['CardId'] = $CardId;
        $data['member_card'] = $UserCardCode;
        $res = Db::name('member')->where('openid',$openid)->update(['CardId'=>$CardId,'member_card'=>$UserCardCode]);
        $str = Db::name('member')->getLastSql();
        Log::record('会员卡更新'.$openid.$CardId.$UserCardCode.'结果'.$str);
        return $res;
    }


    /**
     * 用户激活会员卡信息
     * @return string
     */
    public  function  submit_membercard_user_info($openid ,$CardId ,$UserCardCode){

        if($openid){
            $this->addmember($openid);
        }
        // 更新会员的会员卡信息
        $where['openid'] = $openid;
        $data['CardId'] = $CardId;
        $data['member_card'] = $UserCardCode;
        $data['member_card_status'] = 1;
        //Log::record('会员卡更新'.$openid.$CardId.$UserCardCode);
        $res = Db::name('member')->where($where)->update($data);
        return $res;
    }
    /**
     * 用户激活会员卡信息
     * @return string
     */
    public  function  user_del_card($openid ,$CardId ,$UserCardCode){

        // 更新会员的会员卡信息
        $where['openid'] = $openid;
        $data['member_card_status'] = 2;
        //Log::record('会员卡更新'.$openid.$CardId.$UserCardCode);
        $res = Db::name('member')->where($where)->update($data);
        return $res;
    }



    /**
     * 生成带参数关注二维码
     * @return string
     */
    public  function  qrcode($uid){

        $data['action_name']='QR_LIMIT_STR_SCENE';
        $data['action_info']['scene']['scene_str']=$uid;
        $imageInfo=get_qrcode($data);

        $filename = "qrcode/".$data['action_info']['scene']['scene_str'].".jpg";
        $local_file = fopen($filename, 'w');
        if (false !== $local_file){
            if (false !== fwrite($local_file, $imageInfo)) {
                fclose($local_file);
            }
        }
        return $filename;
    }


    /***
     * 查询用户数是否关注过
     *
     * @return int
     *
     */

    public function get_uid_by_openid($openid){

        $res = Db::name('member')->where(array('openid'=> $openid))->field("uid")->find();
        return $res;

    }

    /**
     * 测试函数
     */
    public function test(){
        $app = Factory::officialAccount(config("EasyWechetConfig"));
        $card = $app->card;
        $users = $card->member_card->getUser('pgeGT0pidQqpfuhit5bXq67AdrZg', '586844661478');

        $openid = Request::instance()->get('openid');
        /*$openid = Request::instance()->get('openid');
        if($openid==null){
            $openid = 'ogeGT0uf2AmhgnEd5blUYf8b10Xs';
        }
        $app = Factory::officialAccount(config("EasyWechetConfig"));
        $users=$app->user->get($openid);
        $message['FromUserName'] = $users['openid'];
        $message['CardId'] = 'pgeGT0pidQqpfuhit5bXq67AdrZg';
        $message['UserCardCode'] = '586844661478';
        $this->user_get_card($message['FromUserName'],$message['CardId'], $message['UserCardCode']);*/
        return $users ;

    }

}